package com.raycloud.java.dada.base;

import com.alibaba.fastjson.JSON;
import com.raycloud.java.dada.result.ResultModel;
import com.raycloud.java.dada.util.HttpRequestUtil;

import java.util.List;
import java.util.Map;

/**
 * Created by hechuan on 2017/6/23.
 *
 * 执行请求并返回接口信息
 */
public abstract class BaseService {

    private ParamService paramService;
    private HttpRequestUtil postSend;
    private String baseUrl ;
    private String sourceId;

    public BaseService(Config config) {
        this.paramService = new ParamService(config.getAppKey(),config.getAppSecret());
        this.postSend = new HttpRequestUtil();
        this.baseUrl = config.getBaserUrl();
        this.sourceId = config.getSourceId();
    }

    /**
     * 执行请求
     * @param object
     * @param action
     * @return
     * @throws Exception
     */
    public String doPost(Object object,String action) throws Exception {
        Map<String, Object> paramMap = paramService.createParam(object, sourceId);
        return postSend.methodPost(baseUrl+ action, paramMap);

    }

    /**
     * 执行请求
     * @param objects
     * @param action
     * @return
     * @throws Exception
     */
    public String doPosts(List<Object> objects, String action)throws Exception{
        Map<String, Object> paramMap = paramService.createParams(objects, sourceId);
        return postSend.methodPost(baseUrl+ action, paramMap);
    }




    public ResultModel strToResultModel(String str)throws Exception{
        ResultModel resultModel = new ResultModel();
        try {
             resultModel = JSON.parseObject(str,ResultModel.class);
        }catch (Exception e){
          throw new Exception("接口返回结果转换异常"+e.getMessage());
        }
        return  resultModel;
    }

}
